import { defineStore } from 'pinia'
import { useToast } from "@/components"
import { AxiosError } from 'axios'

export const useAppStore = defineStore('application', () => {
  const $toast = useToast()

  const msg = {
    success(detail) { $toast.add({ severity: 'success', summary: 'Success', detail, life: 3000 }) },
    error(detail) { $toast.add({ severity: 'error', summary: 'Error', detail, life: 3000 }) },
    warn(detail) { $toast.add({ severity: 'warn', summary: 'Warn', detail, life: 3000 }) },
    info(detail) { $toast.add({ severity: 'info', summary: 'Infor', detail, life: 3000 }) }
  }

  function catchHttpError(res) {
    if (res instanceof AxiosError) {
      const { response } = res

      if (!response?.data?.result) {
        msg.error((response.data.msg))
      } else {
        msg.error((res.message))
      }
    }
    return res;
  }

  return { msg, catchHttpError }
})
